package com.csj.mvvmtest.ui.demo

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import com.csj.mvvm.App
import com.csj.mvvm.event.EventCode
import com.csj.mvvm.event.EventMessage
import com.csj.mvvm.ui.base.BaseActivity
import com.csj.mvvm.ui.base.BaseViewModel
import com.csj.mvvm.ui.base.StartAct
import com.csj.mvvm.ui.base.StartAct.onStart
import com.csj.mvvm.ui.base.StartAct.onStartResult
import com.csj.mvvm.utils.LogUtil
import com.csj.mvvm.utils.StorageUtil
import com.csj.mvvmtest.R
import com.csj.mvvmtest.databinding.ActivitySsdemoBinding
import com.csj.mvvmtest.ui.demo.db.*
import org.greenrobot.eventbus.EventBus
import org.litepal.LitePal
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.thread


class SSDemoActivity : BaseActivity<BaseViewModel, ActivitySsdemoBinding>() {

    companion object {
        const val PICK_FILE = 1
        const val PICK_IMAGES = 2
        const val CREATE_WRITE_REQUEST = 3
        const val ALL_FILES_ACCESS_PERMISSION = 4
    }

    override fun initClick() {
        v.bar.tvTopBarTitle.text = "ScopedStorageDemo"
        v.browseAlbum.setOnClickListener {
            onStart<BrowseAlbumActivity>(mContext)
        }
        v.addImageToAlbum.setOnClickListener {
            val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_splash)
//            val displayName = "${System.currentTimeMillis()}.jpg"
            val displayName = "share.jpg"
            val mimeType = "image/jpeg"
            val compressFormat = Bitmap.CompressFormat.JPEG
            StorageUtil.addBitmapToAlbum(bitmap, displayName, mimeType, compressFormat)
        }
        v.downloadFile.setOnClickListener {
            val fileUrl = "http://guolin.tech/android.txt"
            val fileName = "android.txt"
            StorageUtil.downloadFile(fileUrl, fileName)
        }
        v.pickFile.setOnClickListener {
            pickFileAndCopyUriToExternalFilesDir()
        }
        v.writeRequest.setOnClickListener {
            //多图选择
            onStartResult<BrowseAlbumActivity>(
                mContext,
                PICK_IMAGES,
                Intent().putExtra("pick_files", true)
            )
        }
        v.manageExternalStorage.setOnClickListener {
            requestAllFilesAccessPermission()
        }
        v.eventPush.setOnClickListener {
            App.post(EventMessage(EventCode.REFRESH))
        }
    }

    override fun initData() {

        thread {
            var car: Car? = null
            try {
                car  = LitePal.find(Car::class.java, 1)
            } catch (e: Exception) {
                e.printStackTrace()
            }
//            val albumToUpdate = LitePal.find<Car>(1)
            if (car == null) {
                var car1: Car
                var carBase: CarBase
                var carBody: CarBody
                var carEngine: CarEngine
                var carGearbox: CarGearbox
                //测试数据库15条
                for (i in 1..15) {
                    carBase = CarBase()
                    carBase.price = "$i.0万"
                    carBase.cangshang = "厂商$i"
                    carBase.jibie = if (i % 2 == 0) "轿车" else "SUV"
                    carBase.nengyuan = if (i % 2 == 0) "汽油" else "电动"
                    carBase.shijian = "2021/3/$i"
                    carBase.gonglv = i.toString() + "功率"
                    carBase.niuju = i.toString() + "扭矩"
                    carBase.engine = i.toString() + "00马力"
                    carBase.gearbox = if (i % 2 == 0) "CVT" else "手动"
                    carBase.jiegou = (i + 2).toString() + "座" + i + "车厢"
                    carBase.chesu = "chesu"
                    carBase.youhao = i.toString() + "L"
                    carBase.save()
                    carBody = CarBody()
                    carBody.chang = "460$i"
                    carBody.kuan = "180$i"
                    carBody.gao = "145$i"
                    carBody.zhouju = "270$i"
                    carBody.lidi = "14$i"
                    carBody.chemenshu = "4"
                    carBody.zuoweishu = (i + 2).toString() + "座"
                    carBody.youL = (i + 40).toString() + ""
                    carBody.xingliL = (i + 480).toString() + ""
                    carBody.kg = (i + 1400).toString() + ""
                    carBody.save()
                    carEngine = CarEngine()
                    carEngine.xinghao = "型号$i"
                    carEngine.pailiang = (1500 + i).toString() + "mL"
                    carEngine.jinqi = if (i % 2 == 0) "自然吸气" else "涡轮增压"
                    carEngine.qigang = if (i % 2 == 0) "3缸" else "4缸"
                    carEngine.mali = i.toString() + "00马力"
                    carEngine.gonglv = i.toString() + "000P"
                    carEngine.niuju = i.toString() + "扭矩"
                    carEngine.ranliao = if (i % 2 == 0) "92号汽油" else "95号汽油"
                    carEngine.gongyou = if (i % 2 == 0) "92号" else "95号"
                    carEngine.save()
                    carGearbox = CarGearbox()
                    carGearbox.dangwei = "dangwei"
                    carGearbox.leixing = if (i % 2 == 0) "自动挡" else "手动挡"
                    carGearbox.jiancheng = if (i % 2 == 0) "CVT" else "手动"
                    carGearbox.save()
                    car1 = Car()
                    car1.carName = "车辆$i"
                    car1.setCarBase(carBase)
                    car1.setCarBody(carBody)
                    car1.setCarEngine(carEngine)
                    car1.setCarGearbox(carGearbox)
                    car1.save()
                }
            }
            val cs = LitePal.findAll(Car::class.java,true)//把关联表中的数据一起查询出来
            LogUtil.e(cs[0].toString())
        }
    }

    override fun initVM() {
    }

    private fun pickFileAndCopyUriToExternalFilesDir() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        startActivityForResult(intent, PICK_FILE)
    }

    private fun getFileNameByUri(uri: Uri): String {
        var fileName = System.currentTimeMillis().toString()
        val cursor = contentResolver.query(uri, null, null, null, null)
        if (cursor != null && cursor.count > 0) {
            cursor.moveToFirst()
            fileName =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME))
            cursor.close()
        }
        return fileName
    }

    private fun copyUriToExternalFilesDir(uri: Uri, fileName: String) {
        thread {
            val inputStream = contentResolver.openInputStream(uri)
            val tempDir = getExternalFilesDir("temp")
            if (inputStream != null && tempDir != null) {
                val file = File("$tempDir/$fileName")
                val fos = FileOutputStream(file)
                val bis = BufferedInputStream(inputStream)
                val bos = BufferedOutputStream(fos)
                val byteArray = ByteArray(1024)
                var bytes = bis.read(byteArray)
                while (bytes > 0) {
                    bos.write(byteArray, 0, bytes)
                    bos.flush()
                    bytes = bis.read(byteArray)
                }
                bos.close()
                fos.close()
                runOnUiThread {
                    Toast.makeText(this, "成功拷贝到 $tempDir", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    private fun requestAllFilesAccessPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Environment.isExternalStorageManager()) {
            Toast.makeText(
                this,
                "We can access all files on external storage now",
                Toast.LENGTH_SHORT
            ).show()
        } else {
            val builder = AlertDialog.Builder(this)
                .setTitle("Tip")
                .setMessage("We need permission to access all files on external storage")
                .setPositiveButton("OK") { _, _ ->
                    val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                    startActivityForResult(intent, ALL_FILES_ACCESS_PERMISSION)
                }
                .setNegativeButton("Cancel", null)
            builder.show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            PICK_FILE -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    val uri = data.data
                    if (uri != null) {
                        val fileName = getFileNameByUri(uri)
                        copyUriToExternalFilesDir(uri, fileName)
                    }
                }
            }
            PICK_IMAGES -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        //多图 多个文件写入权限
                        val urisToModify =
                            data.getSerializableExtra("checked_uris") as ArrayList<Uri>
                        val editPendingIntent =
                            MediaStore.createWriteRequest(contentResolver, urisToModify)
                        startIntentSenderForResult(
                            editPendingIntent.intentSender, CREATE_WRITE_REQUEST,
                            null, 0, 0, 0
                        )
                    } else {
                        Toast.makeText(this, "Write permissions are granted", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
            }
            CREATE_WRITE_REQUEST -> {
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "Write permissions are granted", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Write permissions are denied", Toast.LENGTH_SHORT).show()
                }
            }
            ALL_FILES_ACCESS_PERMISSION -> {
                requestAllFilesAccessPermission()
            }
        }
    }
}